﻿using System;

namespace TicTacToeControl
{
    public class Board
    {
        private int[,] _board;
        private bool _haveWinner;
        const int DIMENSION = 3;

        public Board()
        {
            _board = new int[DIMENSION, DIMENSION];
            _haveWinner = false;
        }

        public bool PlacePiece(int x, int y, Player player)
        {
            if (IsLegal(x, y))
            {
                _board[x, y] = player.Identity;
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool CheckForWin(Player player)
        {

            //Check horizontals
            for (int y = 0; y < 3; y++)
            {
                if (_board[0, y] == player.Identity && _board[1, y] == player.Identity && _board[2, y] == player.Identity)
                    _haveWinner = true;
            }

            //Check verticals
            for (int x = 0; x < 3; x++)
            {
                if (_board[x, 0] == player.Identity && _board[x, 1] == player.Identity && _board[x, 2] == player.Identity)
                    _haveWinner = true;
            }

            //Check diags
            if (_board[0, 0] == player.Identity && _board[1, 1] == player.Identity && _board[2, 2] == player.Identity)
                _haveWinner = true;
            if (_board[2, 0] == player.Identity && _board[1, 1] == player.Identity && _board[0, 2] == player.Identity)
                _haveWinner = true;

            return _haveWinner;            
        }

        public void ClearBoard()
        {
            Array.Clear(_board, 0, _board.Length);
            _haveWinner = false;
        }

        private bool IsLegal(int x, int y)
        {
            return (_board[x, y] == 0);
        }

    }
}
